package com.example.lock.interceptor;

import com.example.lock.service.DistributeLockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ReleaseLockInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private DistributeLockService distributeLockService;

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        distributeLockService.releaseAllLock();
        DistributeLockService.LOCKS_HOLDER.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        distributeLockService.releaseAllLock();
        DistributeLockService.LOCKS_HOLDER.remove();
    }
}
